<template>
  <piece>
    <piece-item
      @click="getAddress"
      left-icon="location"
      :is-content-left-font-weight="selectedAddress == null"
      :content-left="selectedAddress ? '重新选择' : '选择地址'"
      :content-right="`${selectedAddress?.detailAddress ?? ''} ${selectedAddress?.specificAddress ?? ''}`"
    />
    <piece-item
      @click="callOutTimeOp"
      :left-icon-custom="true"
      left-icon="icon-songdashijian1"
      :content-left="isImmediate ? '尽快送达' : '指定时间'"
      :content-right="arrivalFormatTime"
    />
  </piece>
  <predetermine-datetime-selector
    @timeCallback="timeCallback"
    :content="generatedPredetermineDatesAndTimeRangesInfo?.datesTimes"
    title="选择预送达时间"
    ref="deliveryTimeOpRef"
  />
</template>

<script setup lang="ts">
import { inject, type Ref, watch, ref, computed, onMounted } from 'vue'
import Piece from '@/components/piece/index.vue'
import PieceItem from '@/components/piece/piece-item/index.vue'
import UrlUtils from '@/utils/UrlUtils'
import $API from '@/api'
import type { AddressBookResponse } from '@/types/response/address-book'
import PredetermineDatetimeSelector from '@/components/predetermine-datetime-selector/index.vue'
import {
  PredetermineDateAndTime,
  type GeneratePredetermineDatesAndTimeRangesNeedInfo,
  type GeneratedPredetermineDatesAndTimeRangesInfo
} from '@/components/predetermine-datetime-selector/utils.type'
import GeoCoordinates from '@/types/generic/GeoCoordinates'
import { PredetermineDatesAndTimeRangesGenerator } from '@/components/predetermine-datetime-selector/utils'
import { TimeOperations } from '@/utils/TimeUtils'
const props = defineProps<{
  shopId: number
  shopPredetermineInfo: GeneratePredetermineDatesAndTimeRangesNeedInfo | undefined
  selectedAddress: AddressBookResponse | undefined
}>()
const generatedPredetermineDatesAndTimeRangesInfo = ref<GeneratedPredetermineDatesAndTimeRangesInfo>()
const deliveryTime = ref<number>()
// 用户选择的地址改变了 ==> 更新 配送用时
watch(
  () => props.selectedAddress?.id,
  async () => {
    if (props.shopId == null || props.selectedAddress == null) return
    const result = await $API.shop.shopDeliveryInfoByUserLocation(
      props.shopId,
      new GeoCoordinates().init(props.selectedAddress.longitude, props.selectedAddress.latitude)
    )
    if (!result.success) return
    deliveryTime.value = result.data.deliveryTime
    // 同时
    if (props.shopPredetermineInfo == null) return
    generatedPredetermineDatesAndTimeRangesInfo.value = PredetermineDatesAndTimeRangesGenerator.gen(
      props.shopPredetermineInfo,
      deliveryTime.value
    )!
  },
  { immediate: true }
)
// 获取配送地址
function getAddress() {
  uni.navigateTo({ url: '/pages/address/index' + UrlUtils.encodeParams({ shopId: props.shopId, choose: true }) })
}

const isImmediate = ref(true)
const chooseDeliveryDateAndTime = ref(new PredetermineDateAndTime())
const arrivalFormatTime = computed(() => {
  return isImmediate.value
    ? `预计 ${PredetermineDateAndTime.format(
        generatedPredetermineDatesAndTimeRangesInfo.value?.immediatePredetermineTime
      )} 送达`
    : `${PredetermineDateAndTime.format(chooseDeliveryDateAndTime.value)}`
})

// 【1】调起"送达时间"选择组件
const deliveryTimeOpRef = ref()
function callOutTimeOp() {
  deliveryTimeOpRef.value.callOut()
}
// 【2】当选择时间后的回调
function timeCallback(predetermineDateAndTime: PredetermineDateAndTime) {
  isImmediate.value = generatedPredetermineDatesAndTimeRangesInfo.value!.isImmediateDateAndTime(predetermineDateAndTime)
  if (!isImmediate.value) chooseDeliveryDateAndTime.value = predetermineDateAndTime
}

// 可被访问数据
// 动态计算收货地址id
const addressBookId = computed(() => props.selectedAddress?.id)
// 动态计算指定时间
const specifiedTime = computed(() => {
  if (isImmediate.value) return null
  return new TimeOperations()
    .update(chooseDeliveryDateAndTime.value.dateItem?.ymdFormat, chooseDeliveryDateAndTime.value.timeItem?.time)
    .getCoreDate()
})
defineExpose({
  isImmediate,
  specifiedTime,
  addressBookId
})
</script>

<style scoped></style>
